<template>
    <div class="health-container">
        <div class="loading-overlay" ref="loadingOverlay">
            <el-icon class="loading-icon" :size="40"><Loading /></el-icon>
            <span>正在加载健康数据...</span>
        </div>

        <div class="health-status-header">
            <div class="status-content">
                <div class="status-title">
                    <div class="title-left">
                        <h2>身体状况评估</h2>
                        <p class="status-subtitle">
                            {{ currentMemberId === userInfo.id ? '基于您的健康数据分析' : `基于${currentMemberInfo?.name || '家庭成员'}的健康数据分析` }}
                        </p>
                    </div>
                    <div class="family-members" v-if="familyMembers.length > 0 && userStore.userInfo?.familyRole?.id === 1">
                        <el-dropdown trigger="click" @command="handleMemberChange">
                            <div class="member-selector">
                                <div class="current-member">
                                    <el-avatar :size="36" :src="currentMemberInfo?.avatar" class="member-avatar">
                                        {{ currentMemberInfo?.name?.charAt(0) }}
                                    </el-avatar>
                                    <div class="member-info">
                                        <span class="member-label">当前查看</span>
                                        <span class="member-name">{{ currentMemberInfo?.name || '我' }}</span>
                                    </div>
                                </div>
                                <el-icon class="selector-icon"><arrow-down /></el-icon>
                            </div>
                            <template #dropdown>
                                <el-dropdown-menu class="member-dropdown">
                                    <div class="dropdown-header">
                                        <span>切换成员</span>
                                    </div>
                                    <el-dropdown-item :command="null">
                                        <div class="dropdown-item-content">
                                            <el-avatar :size="32" :src="userInfo.avatar" class="dropdown-avatar">
                                                {{ userInfo.name?.charAt(0) }}
                                            </el-avatar>
                                            <div class="dropdown-member-info">
                                                <span class="dropdown-member-name">我</span>
                                                <span class="dropdown-member-role">组织者</span>
                                            </div>
                                            <el-icon v-if="!currentMemberId" class="active-icon"><Check /></el-icon>
                                        </div>
                                    </el-dropdown-item>
                                    <div class="dropdown-divider"></div>
                                    <el-dropdown-item 
                                        v-for="member in familyMembers" 
                                        :key="member.userId" 
                                        :command="member.userId"
                                    >
                                        <div class="dropdown-item-content">
                                            <el-avatar :size="32" class="dropdown-avatar">
                                                {{ member.name?.charAt(0) }}
                                            </el-avatar>
                                            <div class="dropdown-member-info">
                                                <span class="dropdown-member-name">{{ member.name }}</span>
                                                <span class="dropdown-member-role">家庭成员</span>
                                            </div>
                                            <el-icon v-if="currentMemberId === member.userId" class="active-icon"><Check /></el-icon>
                                        </div>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>

                <div class="status-result">
                    <!-- <span class="status-label">当前状态</span> -->
                    <template v-if="analyzing">
                        <div class="analysis-progress">
                            <p class="progress-text">正在智能分析健康指数...</p>
                            <el-progress 
                                :percentage="analysisProgress" 
                                :show-text="false"
                                :stroke-width="8"
                                class="health-progress"
                            />
                        </div>
                    </template>
                    <template v-else>
                        <span class="status-text" :class="healthLevelClass">{{ healthLevel }}</span>
                    </template>
                </div>
            </div>
        </div>

        <div class="health-info-card">
            <div class="card-header">
                <div class="title-section">
                    <div class="title-content">
                        <h3>{{ currentMemberId === userInfo.id ? '我的饮食信息' : `${currentMemberInfo?.name || '家庭成员'}的饮食信息` }}</h3>
                        <span class="subtitle">管理{{ currentMemberId === userInfo.id ? '您' : currentMemberInfo?.name || '家庭成员' }}的饮食偏好和健康信息</span>
                    </div>
                    <el-button type="primary" @click="showEditDialog = true" class="edit-btn">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        修改信息
                    </el-button>
                </div>
            </div>
            <Transition name="fade" mode="out-in">
                <div class="card-content" :key="currentMemberId">
                    <div class="info-section">
                        <div class="info-row">
                            <div class="info-label">
                                <el-icon>
                                    <Warning />
                                </el-icon>
                                <span>过敏源</span>
                            </div>
                            <div class="tags-container">
                                <el-tag v-for="item in currentMemberInfo?.allergen" :key="item.id" class="info-tag" type="danger"
                                    effect="light">
                                    {{ item.allergenName }}
                                </el-tag>
                                <span v-if="!currentMemberInfo?.allergen?.length" class="empty-text">暂无过敏源</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">
                                <el-icon>
                                    <FirstAidKit />
                                </el-icon>
                                <span>慢性疾病</span>
                            </div>
                            <div class="tags-container">
                                <el-tag v-for="item in currentMemberInfo?.disease" :key="item.id" type="warning" effect="light"
                                    class="info-tag">
                                    {{ item.chronicDiseaseName }}
                                </el-tag>
                                <span v-if="!currentMemberInfo?.disease?.length" class="empty-text">暂无慢性疾病</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">
                                <el-icon>
                                    <Food />
                                </el-icon>
                                <span>饮食习惯</span>
                            </div>
                            <div class="tags-container">
                                <el-tag v-for="item in currentMemberInfo?.preference" :key="item.id" type="success" effect="light"
                                    class="info-tag">
                                    {{ item.preferenceName }}
                                </el-tag>
                                <span v-if="!currentMemberInfo?.preference?.length" class="empty-text">暂无饮食习惯</span>
                            </div>
                        </div>
                    </div>
                </div>
            </Transition>
        </div>

        <el-dialog v-model="showEditDialog" title="编辑饮食信息" width="50%">
            <div class="edit-form">
                <div class="form-item">
                    <div class="form-label">过敏原</div>
                    <el-select v-model="selectedAllergens" multiple filterable :placeholder="'请选择过敏源'"
                        class="edit-select">
                        <div class="options-grid">
                            <el-option v-for="item in allergens" :key="item.id" :label="item.allergenName"
                                :value="item.id" class="grid-option">
                                <el-tag :type="selectedAllergens.includes(item.id) ? '' : 'info'"
                                    :effect="selectedAllergens.includes(item.id) ? 'dark' : 'plain'">
                                    {{ item.allergenName }}
                                </el-tag>
                            </el-option>
                        </div>
                    </el-select>
                </div>

                <div class="form-item">
                    <div class="form-label">慢性疾病</div>
                    <el-select v-model="selectedDiseases" multiple filterable :placeholder="'请选择慢性疾病'"
                        class="edit-select">
                        <div class="options-grid">
                            <el-option v-for="item in diseases" :key="item.id" :label="item.chronicDiseaseName"
                                :value="item.id" class="grid-option">
                                <el-tag :type="selectedDiseases.includes(item.id) ? 'warning' : 'info'"
                                    :effect="selectedDiseases.includes(item.id) ? 'dark' : 'plain'">
                                    {{ item.chronicDiseaseName }}
                                </el-tag>
                            </el-option>
                        </div>
                    </el-select>
                </div>

                <div class="form-item">
                    <div class="form-label">饮食习惯</div>
                    <el-select v-model="selectedPreferences" multiple filterable :placeholder="'请选择饮食习惯'"
                        class="edit-select">
                        <div class="options-grid">
                            <el-option v-for="item in preferences" :key="item.id" :label="item.preferenceName"
                                :value="item.id" class="grid-option">
                                <el-tag :type="selectedPreferences.includes(item.id) ? 'success' : 'info'"
                                    :effect="selectedPreferences.includes(item.id) ? 'dark' : 'plain'">
                                    {{ item.preferenceName }}
                                </el-tag>
                            </el-option>
                        </div>
                    </el-select>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showEditDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleSave">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog
            v-model="showItemEditDialog"
            :title="`编辑${currentEditItem?.physicalItemName || '指标'}`"
            width="30%"
        >
            <div class="edit-item-form">
                <el-form :model="editForm" label-width="100px">
                    <el-form-item :label="'当前值'">
                        <el-input
                            v-model="editForm.content"
                            :placeholder="'请输入数值'"
                            type="number"
                        >
                            <template #append>{{ currentEditItem?.unit }}</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="正常范围">
                        <el-input
                            :model-value="currentEditItem?.normalRange"
                            disabled
                        >
                            <template #append>{{ currentEditItem?.unit }}</template>
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showItemEditDialog = false">取消</el-button>
                    <el-button
                        type="primary"
                        @click="handleItemEdit"
                        :disabled="!currentEditItem"
                    >
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <div class="chart-container">
            <template v-if="chartData?.length && physicalTypes?.length">
                <div class="legend-container">
                    <div class="legend-item">
                        <div class="legend-color" style="background-color: #C03639"></div>
                        <span>偏高</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background-color: #95D475"></div>
                        <span>正常</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background-color: #A0CFFF"></div>
                        <span>偏低</span>
                    </div>
                </div>
                <div id="healthChart" style="width: 100%; height: 600px;"></div>
            </template>
            <template v-else>
                <div class="empty-state">
                    <el-empty description="暂未上传体检报告">
                        <el-button type="primary" @click="goToUpload">
                            前往上传报告
                        </el-button>
                    </el-empty>
                </div>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { AllergenService, DiseaseService, PreferenceService, UserUpdateService } from '@/api/user'
import { getFamilyMembersService, getUserHealthInfoService } from "@/api/family.js"
import {
    Edit,
    Warning,
    FirstAidKit,
    Food,
    Loading,
    User,
    UserFilled,
    ArrowDown,
    Check
} from '@element-plus/icons-vue'
const physicalTypes = ref([])
import { PhysicalTypeService } from '@/api/physical'
import { GetReportInfoService } from '@/api/physical'
import { UpdatePhysicalItemService } from '@/api/physical'
import { nextTick } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { UserScoreService } from '@/api/user'
const score = ref(0)
const getUserScore = async () => {
    // 如果是当前用户，直接从 userInfo 获取
    if (currentMemberId.value === userInfo.value.id) {
        if (userInfo.value.healthScore) {
            score.value = userInfo.value.healthScore;
            return;
        }
    } else if (currentMemberInfo.value?.healthScore) {
        // 如果是其他成员且已有分数，直接使用
        score.value = currentMemberInfo.value.healthScore;
        return;
    }

    analyzing.value = true;
    analysisProgress.value = 0;
    
    // 启动进度条动画
    progressTimer.value = setInterval(() => {
        if (analysisProgress.value < 90) {
            analysisProgress.value += Math.random() * 10;
        }
    }, 300);

    try {
        // 如果是当前用户，不传递参数
        const result = await UserScoreService(
            currentMemberId.value === userInfo.value.id ? null : currentMemberId.value
        );
        
        if (result.code === 200) {
            if (currentMemberId.value === userInfo.value.id) {
                userInfo.value.healthScore = result.data;
            } else {
                currentMemberInfo.value.healthScore = result.data;
            }
            
            analysisProgress.value = 100;
            setTimeout(() => {
                analyzing.value = false;
                score.value = result.data;
            }, 500);
        }
    } catch (error) {
        console.error('获取健康分数失败:', error);
        analyzing.value = false;
    } finally {
        clearInterval(progressTimer.value);
    }
}
// 添加进度条相关的响应式变量
const analyzing = ref(false)
const analysisProgress = ref(0)
const progressTimer = ref(null)

// 在组件卸载时清理定时器
onUnmounted(() => {
    if (progressTimer.value) {
        clearInterval(progressTimer.value)
    }
})

const getAllTypes = async () => {
    const result = await PhysicalTypeService()
    if (result.code === 200)
    {
        physicalTypes.value = result.data
    }
    console.log(physicalTypes.value)
}
getAllTypes();
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const allergens = ref([])
const diseases = ref([])
const preferences = ref([])

const selectedAllergens = ref([])
const selectedDiseases = ref([])
const selectedPreferences = ref([])

const showEditDialog = ref(false)

const getAllergens = async () => {
    const result = await AllergenService()
    if (result.code === 200) {
        allergens.value = result.data
    }
}

const getDiseases = async () => {
    const result = await DiseaseService()
    if (result.code === 200) {
        diseases.value = result.data
    }
}

const getPreferences = async () => {
    const result = await PreferenceService()
    if (result.code === 200) {
        preferences.value = result.data
    }
}

const initSelectedValues = () => {
    selectedAllergens.value = currentMemberInfo.value?.allergen?.map(item => item.id) || []
    selectedDiseases.value = currentMemberInfo.value?.disease?.map(item => item.id) || []
    selectedPreferences.value = currentMemberInfo.value?.preference?.map(item => item.id) || []
}

const handleSave = async () => {
    try {
        const result = await UserUpdateService({
            id: currentMemberId.value,
            name: currentMemberInfo.value.name,
            allergenIds: selectedAllergens.value,
            diseaseIds: selectedDiseases.value,
            preferenceIds: selectedPreferences.value
        })

        if (result.code === 200) {
            ElMessage.success('保存成功')
            // 更新当前成员信息
            currentMemberInfo.value = {
                ...currentMemberInfo.value,
                healthScore: null,
                allergen: allergens.value.filter(item => selectedAllergens.value.includes(item.id)),
                disease: diseases.value.filter(item => selectedDiseases.value.includes(item.id)),
                preference: preferences.value.filter(item => selectedPreferences.value.includes(item.id))
            }
            // 如果是当前用户，同时更新 userInfo
            if (currentMemberId.value === userInfo.value.id) {
                userStore.setUserInfo({
                    ...userInfo.value,
                    healthScore: null,
                    allergen: allergens.value.filter(item => selectedAllergens.value.includes(item.id)),
                    disease: diseases.value.filter(item => selectedDiseases.value.includes(item.id)),
                    preference: preferences.value.filter(item => selectedPreferences.value.includes(item.id))
                })
            }
            getUserScore()
            showEditDialog.value = false
        }
    } catch (error) {
        ElMessage.error('保存失败')
    }
}

// 添加 watch 来监听 showEditDialog
watch(showEditDialog, (newVal) => {
    if (newVal) {
        // 打开对话框时初始化选中值
        initSelectedValues()
    }
})

const chartData = ref([])
let myChart = null

const initChartData = async () => {
    try {
        await getAllTypes()
        const result = await GetReportInfoService(currentMemberId.value === userInfo.value.id ? null : currentMemberId.value)
        if (result?.code === 200 && Array.isArray(result.data))
        {
            chartData.value = result.data
            console.log(chartData.value)
            await nextTick()
            renderChart()
        } else {
            console.error('Invalid data format:', result)
        }
    } catch (error) {
        console.error('获取健康数据失败:', error)
    } finally {
        if (loadingOverlay.value) {
            loadingOverlay.value.style.opacity = '0'
            setTimeout(() => {
                loadingOverlay.value.style.display = 'none'
            }, 500)
        }
    }
}

const loadingOverlay = ref(null)

const renderChart = () => {
    if (!chartData.value?.length || !physicalTypes.value?.length) return

    const chartDom = document.getElementById('healthChart')
    if (!chartDom) return

    // 如果已存在图表实例，先清理掉
    if (myChart) {
        myChart.off('click') // 清理之前的点击事件监听
        myChart.dispose()    // 完全销毁前的图表实例
    }

    myChart = echarts.init(chartDom)

    // 修改 determineTypeStyle 函数
    const determineTypeStyle = (typeId) => {
        const typeItems = chartData.value.filter(item => item.typeId === typeId)
        let hasRed = false
        let hasBlue = false
        let hasGreen = false

        typeItems.forEach(item => {
            if (item.status === 2) hasRed = true        // status为2时是红色
            else if (item.status === 0) hasBlue = true  // status为0时是蓝色
            else if (item.status === 1) hasGreen = true // status为1时是绿色
        })

        // 返回颜色和大小
        if (hasRed) return { color: '#C03639', value: 1.5 }     // 红色，较大
        if (hasBlue) return { color: '#A0CFFF', value: 0.8 }    // 蓝色，较小
        if (hasGreen) return { color: '#95D475', value: 1 }     // 绿色，正常
        return { color: '#5470c6', value: 1 }                    // 默认蓝色，正常
    }

    // 修改数据准备部分
    const data = {
        name: '健康指标',
        children: physicalTypes.value.map(type => {
            const typeItems = chartData.value.filter(item => item.typeId === type.id)
            const style = determineTypeStyle(type.id)
            return {
                name: type.physicalName,
                id: type.id,
                value: style.value, // 使用计算出的大小
                itemStyle: {
                    color: style.color, // 使用计算出的颜色
                    borderWidth: 2,
                    borderColor: '#fff'
                },
                label: {
                    show: true,
                    position: 'inside',
                    fontSize: style.value === 0.8 ? 14 : 16, // 偏小时字体也稍小
                    fontWeight: 'bold',
                    color: '#fff'
                }
            }
        })
    }

    const option = {
        tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255,255,255,0.9)',
            borderColor: '#eee',
            borderWidth: 1,
            padding: [10, 15],
            textStyle: {
                color: '#333'
            },
            formatter: function(params) {
                const data = params.data
                if (data?.itemData) {
                    const item = data.itemData
                    const [min, max] = (item.normalRange || '0-0').split('-')
                    return `
                        <div style="font-weight:bold;color:#333;margin-bottom:5px">
                            ${item.physicalItemName}
                        </div>
                        <div style="color:#666">
                            当前值: <span style="color:#333;font-weight:bold">
                                ${item.content}${item.unit}
                            </span>
                        </div>
                        <div style="color:#666">
                            正常范围: ${min}-${max}${item.unit}
                        </div>
                        <div style="color:#666">
                            状态: <span style="color:${
                                item.status === 0 ? '#A0CFFF' :
                                item.status === 1 ? '#95D475' : '#C03639'
                            }">
                                ${item.status === 0 ? '偏低' :
                                  item.status === 1 ? '正常' : '偏高'}
                            </span>
                        </div>
                    `
                }
                return `<div style="font-weight:bold;color:#333">${data.name}</div>`
            }
        },
        series: [{
            type: 'pie',
            radius: ['30%', '80%'],
            roseType: 'area',
            avoidLabelOverlap: true,
            itemStyle: {
                borderRadius: 8,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: true,
                position: 'inside',
                formatter: '{b}',
                fontSize: 14,
                fontWeight: 'bold',
                color: '#fff'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 16,
                    fontWeight: 'bold'
                },
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            },
            data: data.children
        }, {
            // 添加中心标题
            type: 'pie',
            radius: ['0%', '25%'],
            center: ['50%', '50%'],
            silent: true,
            label: {
                show: true,
                position: 'center',
                formatter: '健康指标',
                fontSize: 16,
                fontWeight: 'bold',
                color: '#303133'
            },
            data: [{
                value: 1,
                name: '健康指标',
                itemStyle: {
                    color: '#fff'
                }
            }]
        }]
    }

    myChart.setOption(option)

    // 添加一个变量来跟踪当前状态
    let isShowingDetail = false
    let currentTypeId = null

    const showOverview = () => {
        isShowingDetail = false
        currentTypeId = null
        myChart.setOption({
            series: [{
                type: 'pie',
                radius: ['30%', '80%'],
                roseType: 'area',
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 8,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'inside',
                    formatter: '{b}',
                    fontSize: 14,
                    fontWeight: 'bold',
                    color: '#fff'
                },
                data: data.children
            }, {
                // 添加中心标题
                type: 'pie',
                radius: ['0%', '25%'],
                center: ['50%', '50%'],
                silent: true,
                label: {
                    show: true,
                    position: 'center',
                    formatter: '健康指标',
                    fontSize: 16,
                    fontWeight: 'bold',
                    color: '#303133'
                },
                data: [{
                    value: 1,
                    name: '健康指标',
                    itemStyle: {
                        color: '#fff'
                    }
                }]
            }]
        })
    }

    // 重新绑定点击事件
    myChart.on('click', function(params) {
        const clickedData = params.data
        if (!isShowingDetail && clickedData.id) {
            const typeItems = chartData.value.filter(item => item.typeId === clickedData.id)
            if (typeItems.length) {
                isShowingDetail = true
                currentTypeId = clickedData.id

                // 取类型名称
                const typeName = physicalTypes.value.find(t => t.id === clickedData.id)?.physicalName || ''

                const detailData = [{
                    name: '返回',
                    value: 1,
                    itemStyle: {
                        color: '#E1E5EB',
                        borderRadius: 8,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: true,
                        position: 'inside',
                        fontSize: 14,
                        fontWeight: 'bold',
                        color: '#606266'
                    },
                    isBack: true
                }, ...typeItems.map(item => {
                    // 根据状态设置不同的大小
                    const getValue = (status) => {
                        switch(status) {
                            case 0: return 0.8;  // 偏低时显示较小
                            case 1: return 1;    // 正常时显示标准大小
                            case 2: return 1.2;  // 偏高时显示较大
                            default: return 1;
                        }
                    };

                    return {
                        name: item.physicalItemName,
                        value: getValue(item.status), // 使用状态来决定大小
                        itemStyle: {
                            color: item.status === 0 ? '#A0CFFF' : // status为0时是蓝色
                                   item.status === 1 ? '#95D475' : // status为1时是绿色
                                   '#C03639',                      // status为2时是红色
                            borderRadius: 8
                        },
                        label: {
                            show: true,
                            position: 'inside',
                            fontSize: 14,
                            fontWeight: 'bold',
                            color: '#fff'
                        },
                        itemData: {
                            ...item
                        }
                    }
                })]

                myChart.setOption({
                    series: [{
                        type: 'pie',
                        radius: ['30%', '80%'],
                        roseType: 'area',
                        minAngle: 12,           // 稍微减小最小角度
                        minShowLabelAngle: 12,  // 相应调整标签最小角度
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderRadius: 8,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: '{b}',
                            fontSize: 14,
                            fontWeight: 'bold',
                            color: '#fff'
                        },
                        data: detailData
                    }, {
                        // 添加中心标题
                        type: 'pie',
                        radius: ['0%', '25%'],
                        center: ['50%', '50%'],
                        silent: true,
                        label: {
                            show: true,
                            position: 'center',
                            formatter: typeName,
                            fontSize: 16,
                            fontWeight: 'bold',
                            color: '#303133'
                        },
                        data: [{
                            value: 1,
                            name: typeName,
                            itemStyle: {
                                color: '#fff'
                            }
                        }]
                    }]
                })
            }
        } else if (clickedData.isBack) {
            showOverview()
        } else if (clickedData.itemData) {
            // 点击具体指标时，显示编辑对话框
            const itemData = {
                ...clickedData.itemData,
                content: Number(clickedData.itemData.content)  // 确保 content 是数字类型
            }
            currentEditItem.value = itemData
            showItemEditDialog.value = true
        }
    })

    // 初始显示概览
    showOverview()

    // 添加窗口大小改变时的自适应
    window.addEventListener('resize', () => {
        myChart?.resize()
    })
}

const showItemEditDialog = ref(false)
const currentEditItem = ref(null)
const editForm = ref({
    content: ''
})

const handleItemEdit = async () => {
    if (!currentEditItem.value) return

    try {
        const result = await UpdatePhysicalItemService({
            itemId: currentEditItem.value.itemId,
            content: Number(editForm.value.content),
            userId: currentMemberId.value === userInfo.value.id ? null : currentMemberId.value
        })

        if (result.code === 200) {
            showItemEditDialog.value = false
            if(currentMemberId.value === userInfo.value.id){
                userInfo.value.healthScore = null
            }else{
                currentMemberInfo.value.healthScore = null
            }
            getUserScore()
            ElMessage.success('更新成功')

            // 更新图表数据和重新渲染
            await initChartData()
        } else {
            throw new Error(result.msg || '更新失败')
        }
    } catch (error) {
        console.error('更新失败:', error.message)
        ElMessage.error(error.message || '更新失败')
    }
}

// 在关闭对话框时重置 currentEditItem
watch(showItemEditDialog, (newVal) => {
    if (!newVal) {
        currentEditItem.value = null
        editForm.value.content = ''
    }
})

// 添加 watch 来同步 currentEditItem 的值到 editForm
watch(currentEditItem, (newVal) => {
    if (newVal) {
        editForm.value.content = newVal.content
    }
})

const router = useRouter()

const goToUpload = () => {
    router.push('/medicalReport')
}


// 修改健康指数计算
const healthScore = computed(() => {
    return score.value || 0
})

// 添加健康等级计算
const healthLevel = computed(() => {
    const score = healthScore.value
    if (score >= 90) return '十分健康'
    if (score >= 75) return '比较健康'
    if (score >= 60) return '亚健康'
    return '危险'
})

// 添加健康等级样式类计算
const healthLevelClass = computed(() => {
    const score = healthScore.value
    if (score >= 90) return 'excellent'
    if (score >= 75) return 'good'
    if (score >= 60) return 'warning'
    return 'danger'
})

const currentMemberId = ref(null)
const currentMemberInfo = ref(null)

// 初始化当前成员ID
const initCurrentMember = () => {
    // 添加测试数据
    if (!userInfo.value.familyMembers) {
        userStore.setUserInfo({
            ...userInfo.value,
            familyMembers: [
                {
                    id: 2,
                    name: '张三',
                    healthScore: 85
                },
                {
                    id: 3,
                    name: '李四',
                    healthScore: 75
                }
            ]
        })
    }
    
    currentMemberId.value = userInfo.value.id
    currentMemberInfo.value = userInfo.value
}

// 处理家庭成员切换
const handleMemberChange = async (memberId) => {
    try {
        let newMemberInfo;
        if (memberId === null || memberId === userInfo.value.id) {
            newMemberInfo = userInfo.value;
        } else {
            // 获取用户健康信息
            const result = await getUserHealthInfoService(memberId);
            if (result.code === 200) {
                newMemberInfo = result.data;
            } else {
                throw new Error(result.msg || '获取用户健康信息失败');
            }
        }

        // 获取新的图表数据
        await getAllTypes();
        const chartResult = await GetReportInfoService(
            memberId === userInfo.value.id ? null : memberId
        );

        // 一次性更新所有状态
        currentMemberId.value = memberId;
        currentMemberInfo.value = newMemberInfo;
        score.value = newMemberInfo?.healthScore || 0;
        
        if (chartResult?.code === 200 && Array.isArray(chartResult.data)) {
            chartData.value = chartResult.data;
            await nextTick();
            renderChart();
        }

        // 如果需要重新计算健康分数
        if (!newMemberInfo?.healthScore) {
            getUserScore();
        }
    } catch (error) {
        console.error('更新数据失败:', error);
        ElMessage.error(error.message || '更新数据失败');
    }
}

// 添加家庭成员相关变量
const familyMembers = ref([])

// 获取家庭成员数据
const fetchFamilyMembers = async () => {
    // 只在用户是家庭组织者时获取家庭成员
    if (!userStore.userInfo?.familyRole || userStore.userInfo.familyRole.id !== 1) return;
    
    try {
        const result = await getFamilyMembersService()
        if (result.code === 200) {
            familyMembers.value = result.data
        }
    } catch (error) {
        console.error('获取家庭成员失败:', error)
    }
}

// 修改 onMounted
onMounted(async () => {
    await Promise.all([
        getAllergens(), 
        getDiseases(), 
        getPreferences(), 
        getAllTypes(),
        fetchFamilyMembers() // 添加获取家庭成员
    ])
    initSelectedValues()
    initCurrentMember()
    initChartData()
    getUserScore()
})

onUnmounted(() => {
    if (myChart) {
        myChart.off('click') // 清理点击事件监听
        myChart.dispose()    // 销毁图表实例
        myChart = null      // 重置图表实例
    }
})
</script>

<style scoped>
.health-container {
    padding: 32px;
    max-width: 1200px;
    margin: 0 auto;
}

.health-status-header {
    text-align: center;
    margin-bottom: 40px;
    background: white;
    border-radius: 12px;
    padding: 32px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    position: relative;
}

.status-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 24px;
}

.status-title {
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
    width: 100%;
}

.title-left {
    text-align: center;
}

.title-left h2 {
    margin: 0;
    font-size: 28px;
    color: #303133;
    margin-bottom: 8px;
}

.status-subtitle {
    margin: 0;
    color: #909399;
    font-size: 14px;
}

.status-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.status-label {
    font-size: 16px;
    color: #606266;
}

.status-text {
    font-size: 24px;
    font-weight: bold;
    padding: 8px 24px;
    border-radius: 20px;
}

.status-text.excellent {
    color: #67C23A;
    background: #f0f9eb;
}

.status-text.good {
    color: #409EFF;
    background: #ecf5ff;
}

.status-text.warning {
    color: #E6A23C;
    background: #fdf6ec;
}

.status-text.danger {
    color: #F56C6C;
    background: #fef0f0;
}

.health-info-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    overflow: hidden;
}

.card-header {
    padding: 24px;
    border-bottom: 1px solid #f0f0f0;
}

.title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.title-content h3 {
    margin: 0;
    font-size: 20px;
    color: #303133;
    margin-bottom: 4px;
}

.subtitle {
    font-size: 14px;
    color: #909399;
}

.edit-btn {
    display: flex;
    align-items: center;
    gap: 6px;
}

.card-content {
    padding: 24px;
    position: relative;
    width: 100%;
}

.info-section {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.info-row {
    display: flex;
    align-items: flex-start;
    gap: 24px;
}

.info-label {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 120px;
    color: #606266;
    font-size: 15px;
}

.info-label .el-icon {
    font-size: 18px;
}

.tags-container {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 8px;
    padding: 4px 0;
}

.info-tag {
    margin: 0;
    font-size: 13px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 32px;
    transition: all 0.3s ease;
}

.info-tag:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-text {
    color: #909399;
    font-size: 14px;
    font-style: italic;
    grid-column: 1 / -1;
}

:deep(.el-tag span) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
}

.chart-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
    min-height: 400px;
    position: relative;
}

.legend-container {
    position: absolute;
    left: 30px;
    top: 30px;
    z-index: 1;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 10px;
}

.legend-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.legend-item:last-child {
    margin-bottom: 0;
}

.legend-color {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 8px;
}

.legend-item span {
    font-size: 14px;
    color: #606266;
}

/* 对话框样式 */
.edit-form {
    padding: 20px 0;
}

.form-item {
    margin-bottom: 24px;
}

.form-label {
    margin-bottom: 8px;
    font-weight: 500;
    color: #606266;
}

.edit-select {
    width: 100%;
}

.options-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    padding: 8px;
}

.grid-option {
    height: auto !important;
    padding: 4px !important;
}

:deep(.el-select-dropdown__item) {
    padding: 0 !important;
}

:deep(.el-tag) {
    width: 100%;
    text-align: center;
    margin: 0;
}

/* 选中项样式 */
:deep(.el-select__tags) {
    flex-wrap: wrap;
    gap: 4px;
}

:deep(.el-select__tags-text) {
    max-width: none;
}

/* 对话框内的标签停果 */
.grid-option:hover .el-tag {
    transform: translateY(-2px);
    transition: transform 0.3s ease;
}

.edit-item-form {
    padding: 20px;
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #fff;
    z-index: 1000;
    transition: opacity 0.5s ease;
}

.loading-icon {
    animation: rotate 2s linear infinite;
    color: var(--el-color-primary);
    margin-bottom: 12px;
}

.loading-overlay span {
    color: #606266;
    font-size: 16px;
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
}

:deep(.el-empty) {
    padding: 40px 0;
}

.analysis-progress {
    text-align: center;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.progress-text {
    font-size: 16px;
    color: #606266;
    margin-bottom: 15px;
}

.health-progress {
    width: 80%;
    margin: 0 auto;
}

.health-progress :deep(.el-progress-bar__outer) {
    border-radius: 4px;
    background-color: #e6f0ff;
}

.health-progress :deep(.el-progress-bar__inner) {
    border-radius: 4px;
    background: linear-gradient(90deg, #409EFF, #64B5F6);
    transition: width 0.3s ease;
}

.family-members {
    position: absolute;
    top: 20px;
    right: 24px;
    z-index: 10;
}

.member-selector {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
    border: 1px solid rgba(0, 0, 0, 0.08);
    gap: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05),
                0 8px 24px rgba(0, 0, 0, 0.03);
}

.member-selector:hover {
    background: rgba(255, 255, 255, 0.98);
    transform: translateY(-2px) scale(1.01);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08),
                0 12px 32px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.12);
}

.current-member {
    display: flex;
    align-items: center;
    gap: 12px;
}

.member-avatar {
    border: 2px solid #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
    transition: all 0.4s ease;
}

.member-selector:hover .member-avatar {
    transform: scale(1.05);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.16);
}

.member-info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.member-label {
    font-size: 12px;
    color: #86868b;
    margin-bottom: 4px;
    font-weight: 500;
    letter-spacing: -0.2px;
}

.member-name {
    font-size: 15px;
    font-weight: 600;
    color: #1d1d1f;
    letter-spacing: -0.3px;
}

.selector-icon {
    font-size: 14px;
    color: #86868b;
    transition: all 0.4s ease;
    margin-left: auto;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.03);
    border-radius: 50%;
}

.member-selector:hover .selector-icon {
    transform: translateY(2px);
    color: #1d1d1f;
    background: rgba(0, 0, 0, 0.06);
}

/* Dropdown Styles */
.member-dropdown {
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(30px);
    border-radius: 16px;
    border: none;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12),
                0 16px 48px rgba(0, 0, 0, 0.08);
    padding: 12px 0;
    min-width: 300px;
    margin-top: 8px;
}

.dropdown-header {
    padding: 8px 20px;
    color: #86868b;
    font-size: 13px;
    font-weight: 600;
    letter-spacing: -0.2px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    margin-bottom: 8px;
}

.dropdown-item-content {
    display: flex;
    align-items: center;
    padding: 12px 20px;
    gap: 16px;
    position: relative;
    transition: all 0.3s ease;
}

.dropdown-avatar {
    border: 1.5px solid rgba(0, 0, 0, 0.08);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.4s ease;
}

.dropdown-member-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.dropdown-member-name {
    font-size: 15px;
    color: #1d1d1f;
    font-weight: 600;
    letter-spacing: -0.3px;
}

.dropdown-member-role {
    font-size: 12px;
    color: #86868b;
    font-weight: 500;
    letter-spacing: -0.2px;
}

.active-icon {
    position: absolute;
    right: 20px;
    color: #0066CC;
    font-size: 18px;
    opacity: 0;
    transform: scale(0.8);
    transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

.el-dropdown-item:hover .active-icon {
    opacity: 1;
    transform: scale(1);
}

.dropdown-divider {
    height: 1px;
    background: rgba(0, 0, 0, 0.08);
    margin: 8px 0;
}

:deep(.el-dropdown-menu__item) {
    padding: 0;
}

:deep(.el-dropdown-menu__item:not(.is-disabled):hover) {
    background-color: rgba(0, 0, 0, 0.03);
}

:deep(.el-dropdown-menu__item:not(.is-disabled):hover) .dropdown-avatar {
    transform: scale(1.08);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

@media (max-width: 768px) {
    .family-members {
        position: relative;
        top: 0;
        right: 0;
        margin-top: 16px;
    }

    .member-selector {
        width: 100%;
        justify-content: space-between;
    }
}

/* 添加过渡效果样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
